<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class M_calendar extends MY_Model 
{
	private $start_date;


	public function new_event($event_details = '',$type = 'school')
	{
		$srt = DateTime::createFromFormat('m/d/Y',$event_details['evt_str']);
		$end = DateTime::createFromFormat('m/d/Y',$event_details['evt_end']);
		//check if date is not false
		if($srt && $end)
		{
			//check if dates are valid dates
			if($this->validateDate($srt->format('m/d/Y'),'m/d/Y') && $this->validateDate($end->format('m/d/Y'),'m/d/Y'))
			{
				//check if start date is lesser than end date
				if($srt->format('U') <= $end->format('U'))
				{
					//adjust day add additional 1 day at the end
					$end->modify( '+1 day' );

					//set the interval to 1 day
					$interval = new DateInterval('P1D');

					//start the dateperiod
					$alldates = new DatePeriod($srt,$interval,$end);	
					
					// vd($alldates);

					if($alldates == TRUE)
					{
						//create uniqe batch id to easily identify an event
						$batch_id = bin2hex(openssl_random_pseudo_bytes(2)).time();
						foreach($alldates as $k => $_date)
						{
							$dates[$k]['event_date'] = $_date->format('Y-m-d');
							$dates[$k]['event_name'] = $event_details['evt_nme'];
							$dates[$k]['event_start'] = $srt->format('Y-m-d');
							$dates[$k]['event_end'] = $end->format('Y-m-d');
							$dates[$k]['event_desc'] = $event_details['evt_desc'];
							$dates[$k]['event_col'] = $event_details['evt_col'];
							$dates[$k]['event_batch_code'] = $batch_id;
							$dates[$k]['event_created_by'] = ucwords(strtolower($this->c_user->lastname.' , '.$this->c_user->firstname));
							$dates[$k]['created'] = NOW;
							

							if(in_array(strtolower($type),['school','section','academic']))
							{
								if($type == 'school'){
									$dates[$k]['for_school'] = 1;
									$dates[$k]['for_academic'] = 0;
									$dates[$k]['for_section'] = 0;	
								}elseif($type == 'section'){
									$dates[$k]['for_school'] = 0;
									$dates[$k]['for_academic'] = 0;
									$dates[$k]['for_section'] = 1;
									$dates[$k]['section_id'] = $event_details['evt_section'];
								}elseif($type == 'academic')
								{
									$dates[$k]['for_school'] = 0;
									$dates[$k]['for_academic'] = 1;
									$dates[$k]['for_section'] = 0;									
								}
							}
						}

						return $this->_insert_event($dates);

					}else{
						return FALSE;
					}

				}else{
					// pd('Start Date Cannot be Greater than End');
					return (object)['stat'=>false,'msg'=>'Start Date Cannot be Greater than End'];		
				}
			}else{
				// pd('wrong date');
				return (object)['stat'=>false,'msg'=>'You have a wrong date'];		
			}	
		}else
		{
			// pd('invalid dates');
			return (object)['stat'=>false,'msg'=>'Invalid Dates'];
		}
	}

	private function _insert_event($data)
	{
		// pd($data);
		$this->db->insert_batch('calendar_of_events',$data);
		$TRUE = ['stat'=>true,'msg'=>'Successfully Set New Event'];
		$FALSE = ['stat'=>false,'msg'=>'Unable to save Event'];
		return $this->db->affected_rows() >=1 ? (object)$TRUE : (object)$FALSE;
	}
	public function get_all_events($year,$month,$type = 'for_school',$section_id = '')
	{
		if($year AND $month)
		{

			$sql = 'SELECT *,
						   day(event_date) as day_of_event
					FROM calendar_of_events
					WHERE '.$type.' = 1
					AND month(event_date) = ?
					AND year(event_date) = ? ';

			if($type == 'for_section')
			{
				$sql.=' AND section_id = ?';
				$result = $this->db->query($sql,[$month,$year,$section_id]);
			}else{
				$result = $this->db->query($sql,[$month,$year]);	
			}
						
			
			
			if($result->num_rows() >= 1)
			{
				foreach($result->result() as $k => $v)
				{
					$events[$v->day_of_event][]= ['name'=>$v->event_name,'col'=>$v->event_col,'ebc'=>$v->event_batch_code];
				}
				
				return $events;
			}else{
				return array();
			}
		}else{
			return array();
		}

	}

	function get_event($event_id)
	{
		$q = $this->db->select('*,date_format(event_start,"%M %e %Y") as date_start,date_format(event_end,"%M %e %Y") as date_end,DATE_FORMAT(event_start,"%m/%d/%Y") as e_start,DATE_FORMAT(event_end,"%m/%d/%Y") as e_end',FALSE)->where('event_batch_code',$event_id)->limit(1)->get('calendar_of_events');
		return $q->num_rows() >=1 ? $q->row() : FALSE;
	}

	function validateDate($date, $format = 'Y-m-d H:i:s')
	{
	    $d = DateTime::createFromFormat($format, $date);
	    return $d && $d->format($format) == $date;
	}

	function delete_event($event_id)
	{
		$this->db->where('event_batch_code',$event_id)->delete('calendar_of_events');
		return $this->db->affected_rows() >=1 ? TRUE : FALSE;
	}

	function edit_event($old_data,$new_data)
	{
		if($old_data && $new_data)
		{
			if($old_data->event_batch_code == $new_data['batch_sos'])
			{

				// pd($old_data);

				$srt = DateTime::createFromFormat('m/d/Y',$new_data['evt_str']);
				$end = DateTime::createFromFormat('m/d/Y',$new_data['evt_end']);

				if($this->delete_event($new_data['batch_sos']))
				{
					//check if dates are valid dates
					if($this->validateDate($srt->format('m/d/Y'),'m/d/Y') && $this->validateDate($end->format('m/d/Y'),'m/d/Y'))
					{
						//check if start date is lesser than end date
						if($srt->format('U') <= $end->format('U'))
						{
							//adjust day add additional 1 day at the end
							$end->modify( '+1 day' );

							//set the interval to 1 day
							$interval = new DateInterval('P1D');

							//start the dateperiod
							$alldates = new DatePeriod($srt,$interval,$end);	
							
							// vd($alldates);

							if($alldates == TRUE)
							{
								//create uniqe batch id to easily identify an event
								$batch_id = bin2hex(openssl_random_pseudo_bytes(2)).time();
								foreach($alldates as $k => $_date)
								{
									$dates[$k]['event_date'] = $_date->format('Y-m-d');
									$dates[$k]['event_name'] = $new_data['evt_nme'];
									$dates[$k]['event_start'] = $srt->format('Y-m-d');
									$dates[$k]['event_end'] = $end->format('Y-m-d');
									$dates[$k]['event_desc'] = $new_data['evt_desc'];
									$dates[$k]['event_col'] = $new_data['evt_col'];
									$dates[$k]['event_batch_code'] = $new_data['batch_sos'];
									$dates[$k]['event_created_by'] =$old_data->event_created_by;
									$dates[$k]['created'] = $old_data->created;
									$dates[$k]['updated'] = NOW;
									
									if($old_data->for_school == 1)
									{
										$dates[$k]['for_school'] = 1;
										$dates[$k]['for_academic'] = 0;
										$dates[$k]['for_section'] = 0;	
									}elseif($old_data->for_section == 1)
									{
										$dates[$k]['for_school'] = 0;
										$dates[$k]['for_academic'] = 0;
										$dates[$k]['for_section'] = 1;
										$dates[$k]['section_id'] = $old_data->section_id;
									}elseif($old_data->for_academic == 1)
									{
										$dates[$k]['for_school'] = 0;
										$dates[$k]['for_academic'] = 1;
										$dates[$k]['for_section'] = 0;									
									}
								}

								return $this->_insert_event($dates);

							}else{
								return FALSE;
							}

						}else{
							// pd('Start Date Cannot be Greater than End');
							return (object)['stat'=>false,'msg'=>'Start Date Cannot be Greater than End'];		
						}
					}else{
						// pd('wrong date');
						return (object)['stat'=>false,'msg'=>'You have a wrong date'];		
					}	


				}else{
					return FALSE;
				}
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}

}

/* End of file m_calendar.php */
/* Location: ./application/models/m_calendar.php */